<template>
  <div>
    <v-navigation-drawer v-model="switchProxy" app expand-on-hover permanent>
    <!-- 树形导航：暂时 -->
      <v-treeview
        :items="navItems"
        item-title="title"
        item-value="id"
        item-children="children"
        open-on-click
        activatable
        density="comfortable"
        @update:activated="(val: unknown) => onTreeActivate(val as string[])"
      >
        <!-- 自定义左侧图标 -->
        <template #prepend="{ item }">
            <v-icon :icon="item.icon || 'mdi-help-circle'" />
        </template>

        <template #toggle="">
        </template>
      </v-treeview>
      <!-- TODO: 自定义导航栏 -->
      <!-- <v-list nav>
            <v-list-item
            v-for="(nav,idx) in navItems"
            :prepend-icon="nav.icon"
            :key="idx"
            :value="idx"
            @click="onClick(nav.toPath)"
            :title="nav.title as string"
            >
            </v-list-item>
      </v-list> -->
      <v-divider opacity="1" />
    </v-navigation-drawer>
  </div>
</template>

<script setup lang="ts">
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['update:modelValue'])

const switchProxy = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

// 路由表生成
  import type { RouteRecordRaw } from 'vue-router'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  console.log('路由表', router.options.routes);
  
  // 遍历路由表，生成导航项
  const deepRoutes = (routes: RouteRecordRaw[]): RouteItem[] =>{ 
    return routes.map((route: RouteRecordRaw) => {
        let children: RouteItem[] = []
        if (route.children) {
             children = deepRoutes(route.children)
        }
        return {
            // 添加空值检查，确保meta和title存在
            id: route.name as string || route.path || '',
            title: route.meta?.title as string || (route.name as string) || '未知页面',
            toPath: route.path || '',
            icon: route.meta?.icon as string || 'mdi-help-circle',
            children: route.meta?.noGroup ? [] : children
        }
    })
  }
  const navItems = computed(() => {
    if (!router.options.routes[0]?.children) return []
    return deepRoutes(router.options.routes[0].children)
  })
  console.log('导航项', navItems.value);

  function onTreeActivate(ids: string[]) {
    const id = ids[ids.length - 1]
    const findById = (nodes: RouteItem[], target: string): RouteItem | null => {
      for (const n of nodes) {
        if (n.id === target) return n
        if (n.children?.length) {
          const got = findById(n.children, target)
          if (got) return got
        }
      }
      return null
    }
    const node = id ? findById(navItems.value, id) : null
    if (node?.toPath) router.push(node.toPath)
  }
</script>

<style lang="less" scoped>

</style>